package servlet;

import bean.AdInfo;
import bean.User;
import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.UserService;
import utils.UuidUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet({"/User", "/UserServlet", "/getAllUser", "/insertUser", "/delUser", "/updateUser", "/getUsername"})
public class UserServlet extends HttpServlet {

    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");// 设置请求参数的编码格式
        response.setContentType("text/html;charset=utf-8");// 设置网页界面相应的代码
        response.setHeader("Access-Control-Allow-Origin", "*");// 允许所有来源访问
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");// 允许指定的请求方法访问
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");// 允许自定义的请求头部

        String type = request.getParameter("type");
        String rtStr = "";

        try {

            // 获取账户余额
            if ("money".equals(type)) {
                User user = getUserInfoById(request, response);
                rtStr = user.getMoney();
                response.getWriter().write(user.getMoney());
            }

            // 获取用户信息
            if ("user".equals(type)) {
                User user = getUserInfoById(request, response);
                rtStr = JSON.toJSONString(user);
                response.getWriter().write(rtStr);
            }

            // 更换用户头像
            if ("icon".equals(type)) {
                rtStr = IconChange(request, response);

            }

            // 余额充值
            if ("charge".equals(type)) {
                // 获取该用户信息
                User user = getUserInfoById(request, response);
                // 用户余额转double
                double userMoney = Double.parseDouble(user.getMoney());

                // 充值金额转double
                String money = request.getParameter("money");
                double chargeMoney = Double.parseDouble(money);

                userMoney += chargeMoney;

                rtStr = "" + userMoney;

                user.setMoney(rtStr);

                int rt = userService.UserMoneyCharge(user);

                response.getWriter().write(rt);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

// 获取请求 URI
        String requestURI = request.getRequestURI();
        UserService userService = new UserService();

        if (requestURI.endsWith("/getAllUser")) {//获取用户信息
            // 处理获取用户列表的逻辑
            List<User> allUser = userService.getAllUser();
            String userJson = JSON.toJSONString(allUser);
            response.getWriter().write(userJson);
        } else if (requestURI.endsWith("/insertUser")) {//插入用户信息
            // 从请求体中获取 JSON 数据
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = request.getReader();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            // 将 JSON 数据转换为 User 对象
            User user = JSON.parseObject(stringBuilder.toString(), User.class);
            System.out.println("用户名：" + user.getUsername());
            System.out.println("昵称：" + user.getNickname());
            System.out.println("密码：" + user.getPsw());
            System.out.println("邮箱：" + user.getEmail());
            // 执行插入用户的逻辑
            userService.insert(user);
        } else if (requestURI.endsWith("/delUser")) {
            BufferedReader reader = request.getReader();
            String username = reader.readLine();
            User user = JSON.parseObject(username, User.class);
            System.out.println("删除的信息为:" + user.getUsername());
            if (username != null) {
                // 执行删除用户信息的操作
                int rowsAffected = userService.delUser(user.getUsername());
                // 根据 rowsAffected 的值返回相应的响应
                if (rowsAffected > 0) {
                    // 删除成功
                    response.getWriter().write("用户信息删除成功");
                } else {
                    // 删除失败
                    response.getWriter().write("用户信息删除失败");
                }
            } else {
                // 请求体中没有读取到有效的用户名
                response.getWriter().write("未提供有效的用户名");
            }
        } else if (requestURI.endsWith("/updateUser")) {
            // 从请求体中获取 JSON 数据
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = request.getReader();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            // 将 JSON 数据转换为 User 对象
            User user = JSON.parseObject(stringBuilder.toString(), User.class);
            System.out.println("用户名：" + user.getUsername());
            System.out.println("昵称：" + user.getNickname());
            System.out.println("密码：" + user.getPsw());
            System.out.println("邮箱：" + user.getEmail());
            System.out.println("余额:" + user.getMoney());
            // 执行插入用户的逻辑
            userService.updateUser(user);
        } else if (requestURI.endsWith("/getUsername")) { //获取所有用户名
            List<String> username = userService.getUsername();
            String s = JSON.toJSONString(username);
            System.out.println(s);
            response.getWriter().write(s);
        }


        System.out.println("---------- User Servlet Runs -----------");
        System.out.println("请求方式: " + request.getMethod());
        System.out.println("请求内容: " + type);
        System.out.println("返回数据: " + rtStr);
    }

    private String IconChange(HttpServletRequest request, HttpServletResponse response) throws Exception {

        User user = getUserInfoById(request, response);

        //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);

            //创建一个标记位，标记当前时候有上传文件的操作
            boolean flag = false;
            for (FileItem item : fileItems) {
                if (item.getName() != null) {
                    flag = true;
                    break;
                }
            }
            //如果有，使用uuid给改图片生成一个唯一的地址
            String imgId = UuidUtil.getUuid() + ".png";
            // --处理form表单提交过来的文件数据
            for (FileItem item : fileItems) {
                //5.当前表单是否是文件表单
                if (!item.isFormField()) {
                    //6.从临时存储文件的地方将内容写入到指定位置
                    File upload = new File(this.getServletContext().getRealPath("img/icon"), imgId);
                    //获取当前图片虚拟路径，如果是存的绝对路径，img的src获取不到
//                    String imgPath = request.getContextPath() + "/img/bubble/" + imgId;
                    String imgPath = "img/icon/" + imgId;
                    item.write(upload);
                    ServletContext context = request.getServletContext();
                    //存到application域中
                    context.setAttribute("imgPath", imgPath);

                    user.setIcon(imgPath);
                }

            }
        }

        int rt = userService.UserIconUpdate(user.getId(), user.getIcon());

        if ("1".equals(user.getIsManager())) {
            response.sendRedirect(request.getContextPath() + "/");
        } else {
            response.sendRedirect(request.getContextPath() + "/User-Info-Page.html");
        }

        return "User Icon Update Success";
    }

    private User getUserInfoById(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String user_id = (String) session.getAttribute("user_id");

        return userService.getUserInfoById(user_id);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
